import Taro from '@tarojs/taro';
import { connect } from '@tarojs/redux';
import defaultShareImg from '../../assets/images/share.jpg';

function withShare(opts = {}) {

  // 设置默认
  // url: `/pages/good/index?id=${goodId}&from=list`
  // const defalutPath = 'pages/index/index?';
  const defalutPath = 'pages/good/index?';
  const defalutTitle = '社区生活家';
  const defaultImageUrl = defaultShareImg;

  return function demoComponent(Component) {
    // redux里面的用户数据
    @connect(({ user }) => ({
      user
    }))
    class WithShare extends Component {
      async componentWillMount() {
        wx.showShareMenu({
          withShareTicket: true
        });

        if (super.componentWillMount) {
          super.componentWillMount();
        }
      }

      // 点击分享的那一刻会进行调用
      onShareAppMessage () {
        console.log(opts)
        const { user } = this.props;
        let { title, imageUrl, path = null, shareUrl = null, } = opts;
       
        // 从继承的组件获取配置
        if (this.$setSharePath && typeof this.$setSharePath === 'function') {
          path = this.$setSharePath();
        }

        // 从继承的组件获取配置
        if (this.$setShareTitle && typeof this.$setShareTitle === 'function') {
          title = this.$setShareTitle();
        }
        // 从继承的组件获取配置
        if (this.$setShareTitle && typeof this.$setShareTitle === 'function') {
          title = this.$setShareTitle();
        }
        // 从继承的组件获取配置
        if (this.$setShareUrl && typeof this.$setShareUrl === 'function') {
          shareUrl = this.$setShareUrl();
        }
        
        // 从继承的组件获取配置
        if (
          this.$setShareImageUrl &&
          typeof this.$setShareImageUrl === 'function'
        ) {
          imageUrl = this.$setShareImageUrl();
        }


        if (!path) {
          path = defalutPath;
        }
        // console.log(this.props.good)
        // const goodId = this.props.good.goodId;
        // 每条分享都补充用户的分享id
        // 如果path不带参数，分享出去后解析的params里面会带一个{''： ''}
        // const sharePath = `${path}&shareFromUser=${user.openid}`;

        let sharePath = ""
        let goodId = ""
        if(shareUrl){
          sharePath = shareUrl;
        }else{
          if(this.props.good ==undefined){
            path ="pages/index/index?"
            sharePath = `${path}&shareFromUser=${user.openid}`;
          }else{
            goodId = this.props.good.goodId;
            sharePath = `${path}&shareFromUser=${user.openid}&id=${goodId}&from=list`;
          }
        }
        console.log('最后跳转的路由 ', sharePath)
        return {
          title: title || defalutTitle,
          path: sharePath,
          imageUrl: imageUrl || defaultImageUrl
        };
      }

      render () {
        return super.render();
      }
    }

    return WithShare;
  };
}

export default withShare;

